package cn.zyx.controller;

import cn.zyx.common.HttpClientUtils;
import cn.zyx.common.exception.DYTException;
import cn.zyx.Config.WeixinLoginProperties;
import cn.zyx.vo.R;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.security.spec.AlgorithmParameterSpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zzp
 * @since 2021/12/18 18:45
 */
@RestController
public class ApiLoginController{
    /**
     * @Author gdh
     * @Description openid接口的获取
     * @param code
     * @return
     * https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
     * https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
     */
    @GetMapping("/wxlogin")
    public R callback(@RequestParam String code){
        System.out.println("-------"+code);
        //1.判断code是否合法
        if(StringUtils.isEmpty(code)){
            throw new DYTException(22008,"登录失败，尝试刷新重新登录!");
        }
        // 2：通过code获取access_token
        String baseAccessTokenUrl = WeixinLoginProperties.WX_OPEN_GATEWAY +
                "?appid=%s" +
                "&secret=%s" +
                "&js_code=%s" +
                "&grant_type=authorization_code";

        System.out.println(baseAccessTokenUrl);
        String accessTokenUrl = String.format(baseAccessTokenUrl, WeixinLoginProperties.WX_OPEN_APP_ID, WeixinLoginProperties.WX_OPEN_APP_SECRET, code);
        System.out.println(accessTokenUrl);
        String result = null;
        try {
            //执行请求，获取微信请求返回得数据  RestTemplate httpClientUtils
            result = new HttpClientUtils().get(accessTokenUrl);
            //对微信返回得数据进行转换
            Gson gson = new Gson();
            Map<String, Object> resultMap = gson.fromJson(result, HashMap.class);
            if (resultMap.get("errcode") != null) {
                throw new DYTException(22006,"微信登录出错!");
            }
            //解析微信用户得唯一凭证openid
            String openid = (String) resultMap.get("openid");
            if (StringUtils.isEmpty(openid)) {
                throw new DYTException(22009,"登录失败，尝试刷新重新登录!");
            }
            //封装返回
            return R.ok().data("openid", openid).data("token","token").data("resultMap",resultMap);
        }catch (Exception e){
            e.printStackTrace();
//            return R.error().code(601).message("微信解析失败");
            return null;
        }
    }



    /*
     *  获取小程序用户基本信息
     */
    @RequestMapping("/phoneNum")
    public Map<String, String> code2Session(String session_key, String encryptedData, String iv) throws Exception {
//        String code = req.getParameter("code");
        //第一步：通过code换取网页授权access_token
//        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=‘你的小程序appid’&secret=‘你的小程序密钥’&js_code="+code+"&grant_type=authorization_code";
//        JSONObject jsonObject = WXAuthUtil.doGetJson(url);
        Map<String,String> map=new HashMap<>();
//        map.put("openid",jsonObject.getString("openid"));
//        map.put("unionid",jsonObject.getString("unionid"));
//        map.put("session_key",jsonObject.getString("session_key"));
        String sessionkey = session_key;
        // 解密
        byte[] encrypData = Base64Utils.decodeFromString(encryptedData);
        byte[] ivData = Base64Utils.decodeFromString(iv);
        byte[] sessionKey = Base64Utils.decodeFromString(sessionkey);
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(sessionKey, "AES");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);// 设置为解密模式

        String resultString = new String(cipher.doFinal(encrypData), "UTF-8");
        JSONObject object = JSONObject.parseObject(resultString);
        map.put("phone",object.getString("phoneNumber"));// 拿到手机号码
        return map;
    }

}
